<?php
namespace app\home\logic;

use app\common\logic\Base;
use think\facade\App;
use think\facade\Request;

class Url extends  Base {
    
    /**
     * @desc 我的链接
     * @param array $params
     * @param int $userId
     * @return array
     * @throws \Exception
     */
    public function index($params, $userId) {
        $where[] = ['user_id', '=', $userId];
        if($params['keyword']) {
            $where[] = ['keyword', 'like', '%'.$params['keyword'].'%'];
        }

        if($params['groupId']) {
            $urlIds = model('UrlGroupRelation')
                ->where('ugr_group_id', '=', $params['groupId'])
                ->column('ugr_url_id');
            $where[] = ['url_id', 'in', $urlIds];
        }

        if($params['channelId']) {
            $urlIds = App::model('UrlChannelRelation')
                ->where('ucr_channel_id', 'in', $params['channelId'])
                ->column('ucr_url_id');
            $where[] = ['url_id', 'in', $urlIds];
        }

        if($params['link']) {
            $where[] = ['link', 'like', '%'.$params['link'].'%'];
        }
        
        if($params['startDate'] && $params['endDate']) {
            $startTime = date('Y-m-d 00:00:00', strtotime($params['startDate']));
            $endTime = date('Y-m-d 23:59:59', strtotime($params['endDate']));
            $where[] = ['create_time', 'between', [$startTime, $endTime]];
        }else{
            if($params['startDate']) {
                $where[] = ['create_time', 'gt', date('Y-m-d 00:00:00', strtotime($params['startDate']))];
            }
            if($params['endDate']) {
                $where[] = ['create_time', 'lt', date('Y-m-d 23:59:59', strtotime($params['endDate']))];
            }
        }
    
        //排序条件
        $order = 'create_time desc';
        if($params['sort']) {
            $order = $params['sort'].' desc';
        }
        $list = App::model('Url')
            ->where($where)
            ->order($order)
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);

        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = $list['data'];
            $today = date('Y-m-d');

            //获取用户配置的域名
            $domainUrl = model('Domain')->getDomain($userId);
            foreach ($list as $k => $v) {
                $shortUrl = $domainUrl.'/'.$v['keyword'];
                $list[$k]['shortUrl'] = $shortUrl;

                //统计今天的访问量
                $todayWhere = [
                    ['url_id', '=', $v['url_id']],
                    ['create_time', 'like', $today.'%']
                ];
                //今日浏览PV
                $list[$k]['todayPv'] = model('UrlLog')->where($todayWhere)->count() ?: 0;
                //今日用户访问UV
                $list[$k]['todayUv'] = model('UrlLog')->where($todayWhere)->group('user_agent')->count() ?: 0;
                //今日IP数
                $list[$k]['todayIp'] = model('UrlLog')->where($todayWhere)->group('ip')->count() ?: 0;
            }
        }

        //分组列表
        $field = [
            'ug_group_id AS groupId',
            'ug_group_name AS groupName'
        ];
        $groupList = model('UrlGroup')
            ->field($field)
            ->where('ug_user_id', '=', $userId)
            ->limit(100)
            ->select();

        //渠道列表
        $field = [
            'uc_channel_id AS channelId',
            'uc_channel_name AS channelName',
            'uc_channel_key AS channelKey',
            'uc_channel_code AS channelCode'
        ];
        $channelList = model('UrlChannel')
            ->field($field)
            ->where('uc_user_id', '=', $userId)
            ->limit(100)
            ->select();

        return [
            'list'        => $list,
            'groupList'   => $groupList ? output_format($groupList) : [],
            'channelList' => $channelList ? output_format($channelList) : [],
            'params'      => $params,
            'pagination'  => $pagination
        ];
    }

    /**
     * @desc 创建链接
     * @param $userId
     * @return array
     * @throws \Exception
     */
    public function build($userId) {
        //分组列表
        $field = [
            'ug_group_id AS groupId',
            'ug_group_name AS groupName'
        ];
        $groupList = model('UrlGroup')
            ->field($field)
            ->where('ug_user_id', '=', $userId)
            ->limit(100)
            ->select();

        //渠道列表
        $field = [
            'uc_channel_id AS channelId',
            'uc_channel_name AS channelName',
            'uc_channel_key AS channelKey',
            'uc_channel_code AS channelCode'
        ];
        $channelList = model('UrlChannel')
            ->field($field)
            ->where('uc_user_id', '=', $userId)
            ->limit(100)
            ->select();
        return [
            'groupList'   => $groupList ? output_format($groupList) : [],
            'channelList' => $channelList ? output_format($channelList) : [],
        ];
    }

    /**
     * @desc 设置链接
     * @param $params
     * @param $userId
     * @return array
     * @throws \Exception
     */
    public function setting($params, $userId) {
        $where = [
            'user_id' => $userId,
            'url_id'  => $params['id'],
        ];
        $info = model('url')->where($where)->find();
        if($info) {
            //获取用户配置的域名
            $info['short_url'] = model('Domain')->getDomain($userId);
        }
        return [
            'params'    => $params,
            'info'      => $info ?: []
        ];
    }
    
    /**
     * @desc 编辑链接
     * @param array $params
     * @param int $userId
     * @return bool
     * @throws \Exception
     */
    public function operateAjax($params, $userId) {
        $request= Request::instance();
        $ip = $request->ip(); //获取客户端IP地址
        $header = $request->header();
        $userAgent = $header['user-agent'];
        
        $data = [
            'user_id'       => $userId,
            'group_id'      => $params['groupId'],
            'channel_id'    => $params['channelId'],
            'link'          => $params['link'],
            'link_type'     => $params['linkType'],
            'user_agent'    => $userAgent,
            'ip'            => $ip,
            'expire_time'   => $params['expireTime'] ?: date('Y-m-d H:i:s', strtotime('+20year')),
            'password'      => $params['password'],
            'params_switch' => $params['paramsSwitch'],
            'remark'        => $params['remark'],
            'modify_time'   => date('Y-m-d H:i:s')
        ];
        $data = array_filter($data, function($arr) {
            if($arr === '' || $arr === null) {
                return false;
            }
            return true;
        });
        
        if($params['action'] == 'add') {
            $data['keyword'] = model('Url')->getUrlKeyword(6);
            $data['create_time'] = date('Y-m-d H:i:s');
            $result = model('Url')->insertGetId($data);
            
        }else {
            $ownWhere = [
                'user_id' => $userId,
                'url_id'  => $params['id'],
            ];
            $linkInfo = model('url')->where($ownWhere)->find();
            if(!$linkInfo) {
                $this->errorCode = EC_HOME_URL_NOT_EXIST;
                return false;
            }

            $result = model('Url')
                ->where([
                    ['url_id', '=', $params['id']],
                    ['user_id', '=', $userId]
                ])
                ->update($data);
        }
        
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }
    
    
    /**
     * @desc 统计
     * @param $params
     * @param $userId
     * @return array
     * @throws \Exception
     */
    public function statistics($params, $userId) {
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('yesterday'));

        //判断该统计是否为自己的
        $ownWhere = [
            'user_id' => $userId,
            'url_id'  => $params['id'],
        ];
        $linkInfo = model('url')->where($ownWhere)->find();
        if(!$linkInfo) {
            return [
                'todayPv'     => 0,
                'todayUv'     => 0,
                'todayIp'     => 0,
                'yesterdayPv' => 0,
                'yesterdayUv' => 0,
                'yesterdayIp' => 0,
                'list'        => [],
                'info'        => []
            ];
        }
    
        //获取用户配置的域名
        $domainUrl = model('Domain')->getDomain($userId);
        $linkInfo['shortUrl'] = $domainUrl.'/'.$linkInfo['keyword'];
        
        //统计今天的访问量
        $todayWhere = [
            ['url_id', '=', $params['id']],
            ['create_time', 'like', $today.'%']
        ];
        $todayPv = App::model('UrlLog')->where($todayWhere)->count();
        $todayUv = App::model('UrlLog')->where($todayWhere)->group('user_agent')->count();
        $todayIp = App::model('UrlLog')->where($todayWhere)->group('ip')->count();
        
        //统计昨天的访问量
        $yesterdayWhere = [
            ['url_id', '=', $params['id']],
            ['create_time', 'like', $yesterday.'%']
        ];
        $yesterdayPv = App::model('UrlLog')
            ->cache($userId.'yesterdayPvStatistics', 86400) //添加数据查询缓存
            ->where($yesterdayWhere)
            ->count();
        $yesterdayUv = App::model('UrlLog')
            ->cache($userId.':yesterdayUvStatistics', 86400) //添加数据查询缓存
            ->where($yesterdayWhere)
            ->group('user_agent')
            ->count();
        $yesterdayIp = App::model('UrlLog')
            ->cache($userId.':yesterdayIpStatistics', 86400) //添加数据查询缓存
            ->where($yesterdayWhere)
            ->group('ip')
            ->count();
        
        //统计最近7天数据
        $list = App::model('UrlLog')
            ->field('url_id, DATE_FORMAT(create_time, "%Y-%m-%d") AS create_date, count(url_id) AS pv')
            ->where('url_id', '=', $params['id'])
            ->group('DATE_FORMAT(create_time, "%Y-%m-%d")')
            ->limit(7)
            ->order('create_date desc')
            ->select()
            ->toArray();

        //数据统计走势图
        $xAxisDate = [];
        $seriesPv = [];
        $seriesUv = [];
        $seriesIp = [];
        if($list) {
            foreach ($list as $k => $v) {
                $where = [
                    ['url_id', '=', $v['url_id']],
                    ['create_time', 'like', $v['create_date'].'%']
                ];
                //该用户设备访问次数
                $uv = App::model('UrlLog')->where($where)->group('user_agent')->count() ?: 0;
                $list[$k]['uv'] = $uv;

                //该ip访问次数
                $ip = App::model('UrlLog')->where($where)->group('ip')->count() ?: 0;
                $list[$k]['ip'] = $ip;

                array_push($xAxisDate, $v['create_date']);
                array_push($seriesPv, $v['pv']);
                array_push($seriesUv, $uv);
                array_push($seriesIp, $ip);
            }
        }
        
        return [
            'todayPv'     => $todayPv,
            'todayUv'     => $todayUv,
            'todayIp'     => $todayIp,

            'yesterdayPv' => $yesterdayPv,
            'yesterdayUv' => $yesterdayUv,
            'yesterdayIp' => $yesterdayIp,

            'list'        => $list,
            'info'        => $linkInfo,

            'xAxisDate'  => json_encode($xAxisDate),
            'seriesPv'   => json_encode($seriesPv),
            'seriesUv'   => json_encode($seriesUv),
            'seriesIp'   => json_encode($seriesIp)
        ];
    }
}
